<?php
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Response::error('Method not allowed', 405);
}

// 获取请求数据
$data = json_decode(file_get_contents('php://input'), true);
if (!$data || !isset($data['username']) || !isset($data['master_key_hash']) || !isset($data['device_id'])) {
    Response::error('Invalid request data');
}

$username = $data['username'];
$master_key_hash = $data['master_key_hash'];
$device_id = $data['device_id'];

try {
    // 验证用户
    $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? AND master_key_hash = ?");
    $stmt->execute([$username, $master_key_hash]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$result) {
        Response::error('Invalid credentials');
    }

    $user_id = $result['id'];

    // 检查设备是否已注册
    $stmt = $pdo->prepare("SELECT id FROM sync_logs WHERE user_id = ? AND device_id = ?");
    $stmt->execute([$user_id, $device_id]);
    
    if (!$stmt->fetch()) {
        // 注册新设备
        $stmt = $pdo->prepare("INSERT INTO sync_logs (user_id, device_id) VALUES (?, ?)");
        $stmt->execute([$user_id, $device_id]);
    }

    // 获取用户的加密数据
    $stmt = $pdo->prepare("SELECT url, username, password, notes FROM entries WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $entries = $stmt->fetchAll(PDO::FETCH_ASSOC);

    Response::success([
        'user_id' => $user_id,
        'device_id' => $device_id,
        'entries' => $entries
    ], 'Login successful');
} catch (PDOException $e) {
    Response::error('Database error: ' . $e->getMessage());
}
?> 